package com.example;

import java.net.MalformedURLException;
import java.net.URL;

import com.example.R;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AsynTaskDemo extends Activity {

	ProgressBar progressBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		URL[] urls = new URL[10];
		for (int i = 0; i < urls.length; i++) {
			try {
				urls[i] = new URL("link to images");
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
		new Download().execute(urls);
	}
	
	class Download extends AsyncTask<URL, Integer, Long> {
		
		@Override
		protected Long doInBackground(URL... arrUrls) {
			int i = 1;
			for (URL url : arrUrls) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				publishProgress(i++ * 100 / arrUrls.length);
			}			
			return (long) arrUrls.length;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			progressBar.setProgress(values[0]);
		}
		
		@Override
		protected void onPostExecute(Long result) {
			Toast.makeText(getBaseContext(), "Downloaded: " + result + " files!", Toast.LENGTH_SHORT).show();
		}
	}
}
